#include "syscall.h"

int i=0;
int j=0;
unsigned int iLock;
unsigned int jLock;

void f1()
{
	int myf1=1;
	Print1("f1: myf1=%d\n", myf1);
	Print2("f1: i=%d j=%d\n", i, j);
	Acquire(iLock);
	i++;
	Print2("f1: i=%d j=%d\n", i, j);
	Release(iLock);

	Acquire(jLock);
	j++;
	Print2("f1: i=%d j=%d\n", i, j);
	Release(jLock);
	Print1("f1: myf1=%d\n", myf1);
	Print("f1 exiting\n");
	Exit(0);
}

void f2()
{
	int myf2=2;
	Print1("f2: myf2=%d\n", myf2);
	Print2("f2: i=%d j=%d\n", i, j);
	Acquire(iLock);
	i++;
	Print2("f2: i=%d j=%d\n", i, j);
	Release(iLock);

	Acquire(jLock);
	j++;
	Print2("f2: i=%d j=%d\n", i, j);
	Release(jLock);
	Print1("f2: myf2=%d\n", myf2);
	Print("f2 exiting\n");
	Exit(0);
}

void f3()
{
	int myf3=3;
	Print1("f3: myf3=%d\n", myf3);
	Print2("f3: i=%d j=%d\n", i, j);
	Acquire(iLock);
	i++;
	Print2("f3: i=%d j=%d\n", i, j);
	Release(iLock);

	Acquire(jLock);
	j++;
	Print2("f3: i=%d j=%d\n", i, j);
	Release(jLock);
	Print1("f3: myf3=%d\n", myf3);
	Print("f3 exiting\n");
	Exit(0);
}

int main()
{
	int mymain=4;
	Print1("Main: mymain=%d\n", mymain);
	Print2("Main: i=%d j=%d\n", i, j);
	iLock = CreateLock("iLock",5);
	jLock = CreateLock("jLock",5);
	Fork(f1);
	Fork(f2);
	Fork(f3);
	Print1("Main: mymain=%d\n", mymain);
	Print("Main exiting\n");
	Exit(0);
}
